<script setup lang="ts">
import { dateFormat, getFormatDictMap } from '@/util/dict'
import { defineAsyncComponent, onMounted, ref } from 'vue'
import { Search, Refresh, View } from '@/util/icons'
import type { MsgTable } from '@/types/msg'
import AuthButton from '@/components/AuthButton.vue'
import AuthLink from '@/components/AuthLink.vue'
import { getInform } from '@/api/msg'
import type { Page } from '@/types'
import type { Sort } from 'element-plus'
import { authXSS } from '@/util/token'

/* 获取对应的字典信息 */
const tableDict = ref<Map<string, string>>()
const statusDict = ref<Map<string, string>>()
// 页面加载
const loading = ref<boolean>(false)
const page = ref<Page<MsgTable>>({
  num: 1,
  size: 10,
  rows: [],
  count: 0
})
const pageN = '公告'

/* 搜索 */
/* 是否展示搜索栏 */
const showSearchBar = ref<boolean>(true)
const searchForm = ref<MsgTable>({
  type: '',
  title: '',
  status: ''
})
// 页面排序
let orderBy: any = {}
// 获取页面数据
function getPageData() {
  loading.value = true
  getInform(page.value, searchForm.value, orderBy)
    .then((data) => {
      page.value = data.data
    })
    .finally(() => {
      setTimeout(() => {
        loading.value = false
      }, 500)
    })
}

onMounted(() => {
  getFormatDictMap('sys_msg', 'head').then((d) => {
    tableDict.value = d
  })
  getFormatDictMap('sys_msg_status', 'val').then((d) => {
    statusDict.value = d
  })
  getPageData()
})

// 重置搜索框
function reSearch() {
  searchForm.value = {
    type: '',
    title: '',
    status: ''
  }
  getPageData()
}

/* 对话框控制 */
const dialogVisible = ref<boolean>(false)

/* 选择器 */
const selectData = ref<MsgTable[]>([])
function onSelect(data: MsgTable[]) {
  selectData.value = data
}

/* 控制器 */
const controlType = ref<'none' | 'del' | 'add' | 'edit' | 'see' | 'soldOut' | 'reSend'>('none')
const dialogTitle = ref('')
// 删除控制
const Del = defineAsyncComponent(() => import('./Del.vue'))
const delData = ref<MsgTable[]>([])
function del(rows: MsgTable[]) {
  controlType.value = 'del'
  dialogTitle.value = `你确定要删除以下${pageN}吗?`
  delData.value = rows
  dialogVisible.value = true
}

const EditData = ref<MsgTable | null>()

// 添加控制
const Add = defineAsyncComponent(() => import('./Add.vue'))
function add(msg?: MsgTable) {
  // 检查有没有传入 数据  从而得知是否是 数据重发
  if (msg) {
    EditData.value = msg
    controlType.value = 'reSend'
  } else {
    controlType.value = 'add'
  }
  dialogTitle.value = `发送${pageN}`
  dialogVisible.value = true
}

//预览
const See = defineAsyncComponent(() => import('./See.vue'))
function see(d: MsgTable) {
  EditData.value = d
  controlType.value = 'see'
  dialogTitle.value = `预览${pageN}`
  dialogVisible.value = true
}

//  页面排序
function sortTable(data: Sort) {
  if (data.prop == 'time') {
    if (data.order == 'ascending') {
      orderBy['time'] = 'asc'
    } else if (data.order == 'descending') {
      orderBy['time'] = 'desc'
    } else {
      delete orderBy['time']
    }
  }
  getPageData()
}

// 下架
function slodOut(d: MsgTable[]) {
  delData.value = d
  controlType.value = 'soldOut'
  dialogTitle.value = `下架以下${pageN}`
  dialogVisible.value = true
}
</script>

<template>
  <div class="page-root">
    <div class="control">
      <div class="search" v-show="showSearchBar">
        <el-form :inline="true">
          <el-form-item :label="tableDict?.get('title') || 'title'">
            <el-input
              v-model="searchForm.title"
              :placeholder="'请输入' + tableDict?.get('title') || 'title'"
            ></el-input>
          </el-form-item>
          <el-form-item :label="tableDict?.get('status') || 'status'">
            <el-select
              v-model="searchForm.status"
              :placeholder="'请选择' + tableDict?.get('status') || 'status'"
            >
              <el-option label="无" value="" />
              <el-option :label="statusDict?.get('1') || '1'" value="1" />
              <el-option :label="statusDict?.get('0') || '0'" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="getPageData">搜索</el-button>
            <el-button :icon="Refresh" @click="reSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="ctl-bts">
        <span class="ctl-l">
          <AuthButton @click="add()" auth-tag="sys:msg:add"></AuthButton>
          <AuthButton
            @click="slodOut(selectData)"
            :disabled="selectData.length == 0"
            auth-tag="sys:msg:sold_out"
          >
          </AuthButton>
          <AuthButton
            @click="del(selectData)"
            :disabled="selectData.length == 0"
            auth-tag="sys:msg:del"
          />
        </span>
        <span class="ctl-r">
          <el-button :icon="Search" circle @click="showSearchBar = !showSearchBar"></el-button>
          <el-button :icon="Refresh" @click="getPageData" circle></el-button>
        </span>
      </div>
    </div>
    <div class="ctx">
      <el-table
        v-loading="loading"
        table-layout="auto"
        :stripe="true"
        :data="page.rows"
        height="100%"
        row-key="mId"
        @sort-change="sortTable"
        @selection-change="onSelect"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column width="150px" prop="title" align="center">
          <template #header>
            {{ tableDict?.get('title') || 'title' }}
          </template>
          <template #default="{ row }">
            <span>{{ row.title }}</span>
          </template>
        </el-table-column>
        <el-table-column width="150px" prop="send" align="center">
          <template #header>
            {{ tableDict?.get('send') || 'send' }}
          </template>
          <template #default="{ row }">
            {{ row['send'] }}
          </template>
        </el-table-column>
        <el-table-column min-width="300px" prop="msg" align="center">
          <template #header>
            {{ tableDict?.get('msg') || 'msg' }}
          </template>
          <template #default="{ row }">
            <span class="msg-box" v-html="authXSS(row['msg']!)"> </span>
          </template>
        </el-table-column>
        <el-table-column sortable="custom" width="150px" prop="time" align="center">
          <template #header>
            {{ tableDict?.get('time') || 'time' }}
          </template>
          <template #default="{ row }">
            <span class="highlight-info">{{ dateFormat(row.time) }}</span>
          </template>
        </el-table-column>
        <el-table-column width="50px" prop="status" align="center">
          <template #header>
            {{ tableDict?.get('status') || 'status' }}
          </template>
          <template #default="{ row }">
            <el-tag :type="row['status'] === '1' ? 'success' : 'danger'">{{
              statusDict?.get(row['status']) || row['status']
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column width="250px" align="center">
          <template #header> 操作 </template>
          <template #default="{ row }">
            <div class="buttons">
              <el-link :icon="View" @click="see(row)">查看</el-link>
              <AuthLink
                v-if="row['status'] == '1'"
                @click="slodOut([row])"
                auth-tag="sys:msg:sold_out"
              />
              <AuthLink v-else @click="add(row)" auth-tag="sys:msg:re_send" />
              <AuthLink auth-tag="sys:msg:del" @click="del([row])" />
            </div>
          </template>
        </el-table-column>
      </el-table>
      <Pagination :page="page" :get-page-data="getPageData" />
    </div>
    <el-dialog
      @closed="controlType = 'none'"
      v-model="dialogVisible"
      :title="dialogTitle"
      top="5vh"
      width="80%"
    >
      <Del
        v-if="controlType == 'del'"
        :refresh="getPageData"
        type="del"
        :table-dict="tableDict!"
        :rows="delData"
        @c-dlg="dialogVisible = false"
      />
      <Add
        v-else-if="controlType == 'add'"
        :refresh="getPageData"
        :d-map="tableDict!"
        @c-dlg="dialogVisible = false"
      />
      <See v-else-if="controlType == 'see'" :d-map="tableDict!" :item="EditData!" />
      <Del
        v-else-if="controlType == 'soldOut'"
        :refresh="getPageData"
        type="soldOut"
        :table-dict="tableDict!"
        :rows="delData"
        @c-dlg="dialogVisible = false"
      />
      <Add
        v-else-if="controlType == 'reSend'"
        :data="EditData!"
        :refresh="getPageData"
        :d-map="tableDict!"
        @c-dlg="dialogVisible = false"
      />
    </el-dialog>
  </div>
</template>
<style scoped lang="less">
@import '@/assets/page_bgl.less';

.msg-box {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  line-clamp: 2;
  box-orient: vertical;
  -webkit-line-clamp: 2;
  /* 设置显示的行数 */
  -webkit-box-orient: vertical;
}
</style>
